package com.eastdigit.system.controller;

import com.eastdigit.servlet.ReqBean;
import com.eastdigit.servlet.RequestAttribute;
import com.eastdigit.servlet.Response;
import com.eastdigit.system.model.Code;
import com.eastdigit.system.service.ICodeService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/code")
public class CodeController {

    @Autowired
    private ICodeService codeService;

    @RequestMapping(value = "/query")
    @ResponseBody
    public JSONObject queryCode(final @RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        return Response.response(codeService.queryTable(reqBean));
    }

    @RequestMapping(value = "/add")
    @ResponseBody
    public JSONObject addCode(
            final @RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        return Response.responseSuccess(codeService.add(getCode(reqBean)));
    }

    @RequestMapping(value = "/update")
    @ResponseBody
    public JSONObject updateCode(final @RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        return Response.responseSuccess(codeService.update(getCode(reqBean)));
    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    public JSONObject removeCode(final @RequestAttribute(ReqBean.NAME) ReqBean reqBean) {
        codeService.delete(reqBean.getInfo("codeId"));
        return Response.responseSuccess();
    }


    @RequestMapping(value = "/typeTree")
    @ResponseBody
    public JSONObject codeTypeTree(@RequestAttribute(ReqBean.NAME) ReqBean reqBean) throws Exception {
        return Response.response(codeService.queryCodeTypeTree());
    }
    /**
     * 从表单获取对象
     *
     * @param reqBean
     * @return
     */
    private Code getCode(ReqBean reqBean) {
        Code code = new Code();
        code.setCodeId(reqBean.getInfo("codeId"));
        code.setCodeValue(reqBean.getInfo("codeValue"));
        code.setCodeName(reqBean.getInfo("codeName"));
        code.setCodeAlias(reqBean.getInfo("codeAlias"));
        code.setCodeOrder(reqBean.getInfoInt("codeOrder"));
        code.setParentCodeId(reqBean.getInfo("parentCodeId"));
        code.setCodeType(reqBean.getInfo("codeType"));
        code.setCanDelete(reqBean.getInfo("canDelete"));
        return code;
    }
}
